<?php

namespace app\api\controller;

use app\common\controller\Api;
use  app\admin\model\Users as userss;
use  think\Db;
use think\Env;
use fast\Random;
use think\Log;
// 声明命名空间
use Obs\ObsClient;

/**
 * 用户相关接口
 */
class Users extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    private $redis;
    private $appid;
    private $secret;
    private $url;

    public function _initialize()
    {
        parent::_initialize();

        $this->redis = redis(Env::get('redis.host'), Env::get('redis.port'), Env::get('redis.pwd'), Env::get('redis.db'));
        $this->appid = Env::get('wechat.appid');
        $this->secret = Env::get('wechat.secret');
        $this->url = Env::get('url.url');
    }


    /**
     * 获取openID接口
     *
     */
    public function get_openid(){
        $code = empty(request()->get('code')) ? $this->error('code不能为空'):request()->get('code');//获取code
        $url = "https://api.weixin.qq.com/sns/jscode2session?appid=" . $this->appid . "&secret=" . $this->secret . "&js_code=" . $code . "&grant_type=authorization_code";

        $result = file_get_contents($url);
        $result = json_decode($result,true);

        if (isset($result['errcode'])){
            $this->error('失败',$result);
        }

        $this->success('成功',$result);
    }

    /**
     * 解密用户手机号
     *
     */
    public function get_phone(){
        $appid  = $this->appid;
        $sessionKey = empty(request()->post('sessionkey')) ? $this->error('sessionkey不能为空'):request()->post('sessionkey');//获取sessionkey
        $iv = empty(request()->post('iv')) ? $this->error('iv不能为空'):request()->post('iv');//获取iv
        $encryptedData = empty(request()->post('encrypteddata')) ? $this->error('encrypteddata不能为空'):request()->post('encrypteddata');//获取encrypteddata


        if (strlen($sessionKey) != 24) {
            $this->error('sessionkey长度不正确');
        }

        $aesKey = base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            $this->error('iv长度不正确');
        }

        $aesIV = base64_decode($iv);

        $aesCipher = base64_decode($encryptedData);

        $result = openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj = json_decode($result);

        if(empty($dataObj)){
            write_log(['appid'=>$appid,'sessionkey'=>$sessionKey,'iv'=>$iv,'encrypteddata'=>$encryptedData]);
            $this->error('解析失败');
        }

        if ($dataObj->watermark->appid !=  $appid){
            $this->error('appid错误');
        }

        $data = json_decode($result,true);
        $this->success('成功',$data);
    }


    /**
     * 用户登录注册接口
     *
     */
    public function add_wechat(){
        $openid = empty(request()->post('openid')) ? $this->error('openid不能为空'):request()->post('openid');//获取openid
        $nickname = empty(request()->post('nickname')) ? $this->error('nickname不能为空'):request()->post('nickname');//获取nickname
        $phone = empty(request()->post('phone')) ? $this->error('phone不能为空'):request()->post('phone');//获取phone
        $image = empty(request()->post('image')) ? $this->error('image不能为空'):request()->post('image');//获取头像
        $pid = empty(request()->post('pid')) ? 0:request()->post('pid');//获取邀请人id
        $did = empty(request()->post('did')) ? 0:request()->post('did');//获取大客户code

        $users = Db::table('fa_users')
            ->where('openid',$openid)
            ->find();

        if ($did !== 0){
            $da_arr = Db::table('fa_big')
                ->where('code',$did)
                ->find();

            if (empty($da_arr)){
                $this->error('绑定大客户不存在');
            }

            $did = $da_arr['id'];

        }

//        $insert_arr = [
//            'openid' => $openid,
//            'nickname' => $nickname,
//            'phone' => $phone,
//            'level' => 1,
//            'invite' => $pid,
//            'image' => $image,
//            'create_time' => date('Y-m-d H:i:s'),
//            'login_time' => date('Y-m-d H:i:s'),
//            'password' => substr($phone,-6),
//        ];

        //write_log($insert_arr);

        if (empty($users)){
            if ($did !== 0){
                if ($users['big_id'] == 0){
                    $insert = Db::table('fa_users')
                        ->insertGetId([
                            'openid' => $openid,
                            'nickname' => $nickname,
                            'phone' => $phone,
                            'level' => 1,
                            'invite' => $pid,
                            'image' => $image,
                            'create_time' => time(),
                            'login_time' => time(),
                            'password' => substr($phone,-6),
                            'big_id' => $did,
                            'binding_time' => time(),
                        ]);
                }else{
                    $insert = 1;
                }

            }else{
                $insert = Db::table('fa_users')
                    ->insertGetId([
                        'openid' => $openid,
                        'nickname' => $nickname,
                        'phone' => $phone,
                        'level' => 1,
                        'invite' => $pid,
                        'image' => $image,
                        'create_time' => time(),
                        'login_time' => time(),
                        'password' => substr($phone,-6),
                    ]);
            }



        }else{

            if ($did !== 0){
                if ($users['big_id'] == 0){
                    $insert = Db::table('fa_users')
                        ->where('id',$users['id'])
                        ->update([
                            'nickname' => $nickname,
                            'phone' => $phone,
                            'image' => $image,
                            'update_time' => time(),
                            'login_time' => time(),
                            'big_id' => $did,
                            'binding_time' => time(),
                        ]);
                }else{
                    $insert = 1;
                }

            }else{
                $insert = Db::table('fa_users')
                    ->where('id',$users['id'])
                    ->update([
                        'nickname' => $nickname,
                        'phone' => $phone,
                        'image' => $image,
                        'update_time' => time(),
                        'login_time' => time(),
                    ]);
            }

        }

        if ($insert !== false){
            $this->success('成功',[]);
        }else{
            $this->error('失败');
        }


    }


    /**
     * 医护端登录
     *
     */
    public function info_login(){
        $username = empty(request()->post('username')) ? $this->error('用户名不能为空'):request()->post('username');//获取用户名
        $password = empty(request()->post('password')) ? $this->error('密码不能为空'):request()->post('password');//获取密码

        //查询手机号是否存在
        $data = Db::table('fa_medic')->where('username',$username)->find();

        if (empty($data)){
            $this->error('账号不存在',[]);
        }

        //判断该账户是否启用
        if ($data['status'] == 0){
            $this->error('账号未启用',[]);
        }

        //判断密码是否正确
        if ($password != $data['password']){
            $this->error('密码错误',[]);
        }

        $token = Random::uuid();
        $this->redis->Set('luying:token:'.$token,json_encode($data),43200);//设置redis


        $arr = [
            'token' => $token,
            'id' => $data['id'],
            'name' => $data['name'],
            'image' => $this->url.$data['image'],
            'type' => $data['type'],
        ];
        $this->success('登录成功',$arr);
    }


    /**
     * 退出登录-医护端
     *
     */
    public function out_info(){
        $token = empty(request()->post('token')) ? $this->error('token不能为空',[]):request()->post('token');//获取token

        $del = $this->redis->del('luying:token:'.$token);

        $this->success('退出成功',$del);
    }


    /**
     * 支付回调
     *
     */
    public function callback(){
        $post = input('');
        //$key = 'o276ETIRLSURdj5ROaQyqz5tv74YzEFm';//商户平台设置的api v3 密码
        $key = 'qL2sK7dZ6xJ7qF9cZ0kG1yR1uX2lX1dZ';//商户平台设置的api v3 密码
        $text = base64_decode($post['resource']['ciphertext']);
        $str = sodium_crypto_aead_aes256gcm_decrypt($text,$post['resource']['associated_data'],$post['resource']['nonce'],$key);
        $res = json_decode($str, true);

        if($res['trade_state'] == 'SUCCESS'){
            //成功操作
            $attach = json_decode($res['attach'],true);//订单数据

            $data_working = Db::table('fa_working')
                ->where('id',$attach['working_id'])
                ->find();

            if (empty($data_working)){
                $visiting_time = '';
                $datess = '';
            }else{
                $date = date("w",strtotime($data_working['date']));

                switch ($data_working['time']){
                    case 1:
                        $tims = '09:00-10:00';
                        break;
                    case 2:
                        $tims = '10:00-11:00';
                        break;
                    case 3:
                        $tims = '11:00-12:00';
                        break;
                    case 4:
                        $tims = '14:00-15:00';
                        break;
                    case 5:
                        $tims = '15:00-16:00';
                        break;
                    case 6:
                        $tims = '16:00-17:00';
                        break;
                }

                switch ($date){
                    case 0:
                        $day = '星期天';
                        break;
                    case 1:
                        $day = '星期一';
                        break;
                    case 2:
                        $day = '星期二';
                        break;
                    case 3:
                        $day = '星期三';
                        break;
                    case 4:
                        $day = '星期四';
                        break;
                    case 5:
                        $day = '星期五';
                        break;
                    case 6:
                        $day = '星期六';
                        break;
                    default:
                        $day = '';
                        break;
                }

                $timss = explode('-',$tims);

                $visiting_time = $data_working['date'].' '.$day.' '.$tims;
                $datess = $data_working['date'];
                $begin_time = strtotime($data_working['date'].' '.$timss[0]);
                $end_time = strtotime($data_working['date'].' '.$timss[1]);
            }


            $cha_arr = Db::table('fa_registration')
                ->where(['user_id'=>$attach['user_id'],'info_id'=>$attach['info_id'],'working_id'=>$attach['working_id']])
                ->find();

            if (empty($cha_arr)){
                //开启事务
                Db::startTrans();

                $user_arr = Db::table('fa_users')
                    ->where('id',$attach['user_id'])
                    ->find();

                $integral =  floor($res['amount']['total']/10);

                //加积分
                if (!empty($user_arr['invite'])){
                    $update = Db::table('fa_users')
                        ->where('id',$user_arr['invite'])
                        ->setInc('integral',$integral);
                }else{
                    $update = 1;
                }


                $insert = Db::table('fa_registration')
                    ->insertGetId([
                        'user_id' => $attach['user_id'],
                        'info_id' => $attach['info_id'],
                        'medic_id' => $attach['medic_id'],
                        'project' => $attach['project'],
                        'visiting_time' => $visiting_time,
                        'begin_time' => $begin_time,
                        'end_time' => $end_time,
                        'status' => '待就诊',
                        'price' => $res['amount']['total'],
                        'create_time' =>time(),
                        'working_id' =>$attach['working_id'],
                        'code' =>$res['out_trade_no'],
                        'date' =>$datess,
                        'project_ids' =>$attach['project_ids'],
                    ]);

                if (($insert > 0) && ($update !== false)){
                    //提交事务
                    Db::commit();
                    //$a = Log::write($insert);
                    write_log($insert);
                    return 1;
                }else{
                    //回滚事务
                    Db::rollback();
                    //Log::write();
                    write_log(['code'=>4001,'insert'=>$insert,'update'=>$update,'user_id'=>$attach['user_id']]);
                    return 2;
                }
            }




        }else{
            //$a = Log::write($res);
            write_log($res);
        }

        return 1;
    }

    /**
     * 支付回调-测试
     *
     */
    public function callbacks(){
        $post = input('');
        //$key = 'o276ETIRLSURdj5ROaQyqz5tv74YzEFm';//商户平台设置的api v3 密码
        $key = 'qL2sK7dZ6xJ7qF9cZ0kG1yR1uX2lX1dZ';//商户平台设置的api v3 密码
        $text = base64_decode($post['resource']['ciphertext']);
        $str = sodium_crypto_aead_aes256gcm_decrypt($text,$post['resource']['associated_data'],$post['resource']['nonce'],$key);
        $res = json_decode($str, true);

        if($res['trade_state'] == 'SUCCESS'){
            //成功操作
            $attach = json_decode($res['attach'],true);//订单数据


            $cha_arr = Db::table('fa_registration')
                ->where(['id'=>$attach['order_id']])
                ->find();

            if (!empty($cha_arr)){
                if ($cha_arr['status'] != '待支付'){
                    return 1;
                }

                //开启事务
                Db::startTrans();
                $user_arr = Db::table('fa_users')
                    ->where('id',$attach['user_id'])
                    ->find();

                $integral =  floor($res['amount']['total']/100/10);

                //加积分
                if (!empty($user_arr['invite'])){
                    $update = Db::table('fa_users')
                        ->where('id',$user_arr['invite'])
                        ->setInc('integral',$integral);

                    $logss = Db::table('fa_integral_log')
                        ->insertGetId([
                            'user_id' => $attach['user_id'],
                            'info_id' => $attach['info_id'],
                            'integral' => $integral,
                            'create_time' => time(),
                            'type' => 2,
                            'way' => 2,
                        ]);
                }else{
                    $update = 1;
                    $logss = 1;
                }


                $insert = Db::table('fa_registration')
                    ->where('id',$attach['order_id'])
                    ->update([
                        'status' => '待确认',
                        'update_time' => time(),
                    ]);
                if (($insert !== false) && ($update !== false) && ($logss !== false)){
                    //提交事务
                    Db::commit();
                    return 1;
                }else{
                    //回滚事务
                    Db::rollback();
                    write_log(['code'=>4001,'insert'=>$insert,'update'=>$update,'user_id'=>$attach['user_id']]);
                    return 2;
                }
            }
            write_log($res);
        }else{
            write_log($res);
        }

        return 1;
    }

    /**
     * 支付回调-周边产品
     *
     */
    public function callbackss(){
        $post = input('');
        //$key = 'o276ETIRLSURdj5ROaQyqz5tv74YzEFm';//商户平台设置的api v3 密码
        $key = 'qL2sK7dZ6xJ7qF9cZ0kG1yR1uX2lX1dZ';//商户平台设置的api v3 密码
        $text = base64_decode($post['resource']['ciphertext']);
        $str = sodium_crypto_aead_aes256gcm_decrypt($text,$post['resource']['associated_data'],$post['resource']['nonce'],$key);
        $res = json_decode($str, true);

        if($res['trade_state'] == 'SUCCESS'){
            //成功操作
            $attach = json_decode($res['attach'],true);//订单数据


            $cha_arr = Db::table('fa_orders')
                ->where(['id'=>$attach['order_id']])
                ->find();

            if (!empty($cha_arr)){

                if ($cha_arr['status'] != 0){
                    return 1;
                }

                $insert = Db::table('fa_orders')
                    ->where('id',$attach['order_id'])
                    ->update([
                        'status' => 1,
                        'update_time' => time(),
                    ]);
                if ($insert !== false){
                    return 1;
                }else{
                    write_log(['code'=>4001,'insert'=>$insert,'order_id'=>$attach['order_id']]);
                    return 2;
                }
            }
            write_log($res);
        }else{
            write_log($res);
        }

        return 1;
    }


    /**
     * 上传
     *
     */
    public function uploading(){
        require '../vendor/obs/obs-autoloader.php';

        //$namess = empty(request()->post('name')) ? '':request()->post('name');
        $namess = request()->post('name');
        $file = $_FILES['file'];


        //var_dump($file);die();
        //获取表单上传文件
        if ($file) {
            $tmpPname = $file['name'];//客户端文件的原名称
            $tmpP = $file['tmp_name'];//文件被上传后在服务端储存的临时文件名

            if ($tmpP) {
                //获取文件后缀
                $suffix = pathinfo($tmpPname, PATHINFO_EXTENSION);
//                $filetype = ['jpg', 'jpeg', 'gif', 'bmp', 'png','mp3','mp4','pdf'];
//                if (!in_array($suffix, $filetype)) {
//                    $this->error('格式不正确');
//                }

//                $dir_path = "./log/logs";
//                if (!file_exists($dir_path)){
//                    mkdir($dir_path,755,1);
//                }

                $name = time() . uniqid() . '.' . $suffix; //临时文件名称

                //$f_path = $dir_path . '/' . $name; //临时文件路劲


                //if (move_uploaded_file($tmpP, $f_path)) {
                    //开始obs上传,引入文件
                    // 创建ObsClient实例
                    $obsClient = new ObsClient([
                        'key' => 'W2O4GDBTRQIFRODHXVDU',
                        'secret' => '8jpkOkdEFdgZh53DzZnCkIrHczPfIWc8RVK1p9iQ',
                        'endpoint' => 'https://obs.cn-south-1.myhuaweicloud.com'
                    ]);

                    try {

                    $resp = $obsClient->putObject([
                        'Bucket' => 'obs-c95m',
                        'Key' => 'luyin/'.$name,
                        //'SourceFile' => $f_path  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                        'SourceFile' => $tmpP  // localfile为待上传的本地文件路径，需要指定到具体的文件名
                    ]);
                    //unlink($f_path); //上传本地临时文件

                        $img_name =  'https://img.looin.cn/luyin/'.$name;
                        if (!empty($namess)){
                            $ar = [
                                'img_name' => $img_name,
                                'name' => $namess,
                                'suffix' => $suffix,
                            ];
                        }else{
                            $ar = [
                                'img_name' => $img_name,
                                'name' => $namess,
                                'suffix' => $suffix,
                            ];
                        }
                        $this->success('成功',$ar);


                    } catch (\Obs\ObsException $obsException){
                        $this->error($obsException->getExceptionCode(),$obsException->getExceptionMessage());
                    }


                //}

            }
        }



    }


    /**
     * 获取分享码
     *
     */
    public function get_qrcode(){
        $pid = empty(request()->get('pid')) ? $this->error('pid不能为空',[]):request()->get('pid');
        //$str = '{"scene":"pid='.$pid.'"}';//测试
        //$str = '{"scene":"pid='.$pid.'","page":"pages/login/login"}';
        //$str = '{"scene":"'.$pid.'","page":"pages/login/login"}';
        $str = '{"scene":"pid*'.$pid.'","page":"pages/login/login"}';

        $appid = $this->appid;
        $secret = $this->secret;
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret;

        $access_toke = $this->redis->Get('access_toke');//设置redis

        if ($access_toke == false){
            $result = file_get_contents($url);
            $result = json_decode($result,true);

            if (isset($result['errcode'])){
                $this->error('token获取失败',$result);
            }
            //将access_toke存redis
            $this->redis->Set('access_toke',$result['access_token'],7000);//设置redis
            $access_toke = $result['access_token'];
        }

        //header('Content-type: image/jpeg');
        $urls = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_toke;

        $result = http($urls,$str,'POST',[],true);

        $results = json_decode($result,true);


        if (isset($results['errcode'])){
            if ($results['errcode'] == 40001){
                $result = file_get_contents($url);
                $result = json_decode($result,true);

                if (isset($result['errcode'])){
                    $this->error('token获取失败',$result);
                }
                //将access_toke存redis
                $this->redis->Set('access_toke',$result['access_token'],7000);//设置redis
                $access_toke = $result['access_token'];

                $urls = 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token='.$access_toke;

                $result = http($urls,$str,'POST',[],true);
            }else{
                return $result;
            }

        }

        $img=base64_encode($result);

        //echo '<img src="data:image/jpeg;base64,'.$img.'"/>';
        $this->success('成功',$img);
    }


    /**
     *发送短信
     *
     */
    public function sms(){
        $mobile = empty(request()->post('mobile')) ? $this->error('mobile不能为空',[]):request()->post('mobile');//获取手机号

        $code = get_strings(6,2);


        $pan = $this->redis->Get('luying:code:'.$mobile);//设置redis

        if ($pan !== false){
            $this->error('短信验证码已发送,请勿重复操作',[]);
        }

        //将验证码存redis
        $this->redis->Set('luying:code:'.$mobile,$code,120);//设置redis

        $sms= send_sms('SMS_21071300010',$mobile,['code'=>$code]);
        //$sms= 1;

        if ($sms != 1){
            $this->error('发送失败',[]);
        }else{
            $this->success('发送成功',[$code]);
            //$this->success('发送成功',[]);
        }
    }

    /**
     * 验证业务员手机号是否正确
     *
     */
    public function check(){
        //$username = empty(request()->post('username')) ? $this->error('业务员id不能为空'):request()->post('username');
        $mobile = empty(request()->post('mobile')) ? $this->error('手机号不能为空'):request()->post('mobile');

        $mobile = is_phone($mobile);//验证手机号

        if ($mobile === false){
            $this->error('手机号格式错误',[]);
        }

        $admin_arr = Db::table('fa_admin')
            ->where(['phone'=>$mobile,'salesman'=>1])
            ->find();

        if (empty($admin_arr)){
            $this->error('业务员手机号错误',[]);
        }

        $this->success('验证成功',[]);

    }


    /**
     * 业务端登录
     *
     */
    public function salesman_login(){
        //$username = empty(request()->post('username')) ? $this->error('业务员id不能为空'):request()->post('username');
        $mobile = empty(request()->post('mobile')) ? $this->error('手机号不能为空'):request()->post('mobile');
        $code = empty(request()->post('code')) ? $this->error('验证码不能为空'):request()->post('code');

        $mobile = is_phone($mobile);//验证手机号

        if ($mobile === false){
            $this->error('手机号格式错误',[]);
        }

        $admin_arr = Db::table('fa_admin')
            ->where(['phone'=>$mobile,'salesman'=>1])
            ->find();

        if (empty($admin_arr)){
            $this->error('业务员手机号错误',[]);
        }

        if ($admin_arr['status'] == 'hidden'){
            $this->error('业务员处于关闭状态',[]);
        }

        $pan_code = $this->redis->Get('luying:code:'.$mobile);//设置redis

        //判断验证码是否正确
        if ($pan_code == false){
            $this->error('验证码过期',[]);
        }

        //判断验证码是否正确
        if ($pan_code != $code){
            $this->error('验证码错误',[]);
        }

        $token = Random::uuid();
        $this->redis->Set('luying:token:'.$token,json_encode($admin_arr),43200);//设置redis


        $arr = [
            'token' => $token,
//            'id' => $data['id'],
////            'name' => $data['name'],
////            'image' => $this->url.$data['image'],
////            'type' => $data['type'],
        ];
        $this->success('登录成功',$arr);


    }






}
